<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

class Gallery_model extends CI_Model {

	public function __construct(){
		parent::__construct();
		$this->url = base_url()."assets/upload/";
		$this->path = realpath(APPPATH . "../assets/upload");
	}


	public function single_upload($em = null,$ajax = false, $redirect = true, $notice = true){
		$conf = array(
			'upload_path' => $this->path,
			'allowed_types' => 'gif|jpg|png|jpeg|JPG|JPEG|PNG|GIF',
			'max_size' => '10240',
			'encrypt_name' => true,
			'max_width' => '3000',
			'max_height' => '3000'
		);

		$this->load->library('upload', $conf);
		if(!$this->upload->do_upload('userfile')):
			if(!$ajax && $notice):
				$this->session->set_flashdata('error',$this->upload->display_errors());
			elseif($ajax):
				$status = 'error';
				$msg = $this->upload->display_errors('','');
			endif;

		else:
			$data = $this->upload->data();
			if(!$ajax && $notice):
				$this->session->set_flashdata('success','Upload hình thành công');
			elseif($ajax):
				$status = 'success';
				$msg = 'File upload successfully';
			endif;

			$this->insert_img($data, $em);
		endif;

		//create thumb
		if(!empty($data)):
			$conf = array(
				'source_image' => $data['full_path'],
				'new_image' => $this->path . '/thumbs',
				'maintain_ratio' => true,
				'width' => '350','height' => '350'
			);
			$this->load->library('image_lib',$conf);
			$this->image_lib->resize();
		endif;

		if($ajax):
			$source = null;
			if(!empty($data))
				$source = array(
					'thumb'=>base_url().'assets/upload/thumbs/'.$data['file_name'],
					'img'=>base_url().'assets/upload/'.$data['file_name']
				);
			echo json_encode(array('status'=>$status,'msg'=>$msg,'thumb'=>$source['thumb'],'img'=>$source['img']));
		else:
			if($redirect)
				redirect('/admin/gallery/upload');
			else
				return $data;
		endif;
	}

	protected function insert_img($data = array(), $em){

		$img = new \Entity\ShImage();
		$img->setName($data['file_name']);
		$img->setDimension($data['image_width'].'x'.$data['image_height']);
		$img->setSize($data['file_size']);
		
		$em->persist($img);
		$em->flush();
	}

	public function delete(){
		$this->db->delete('image', array('name' => $this->input->post('img')));

		$arr = explode('.', $this->input->post('img'));
		$img = url_title(array_shift($arr));
		$ext = url_title(array_pop($arr));

		$link = $this->path. DIRECTORY_SEPARATOR . $img.'.'.$ext ;
		if(file_exists($link)):
			@unlink($link);
			@unlink($this->path. DIRECTORY_SEPARATOR . 'thumbs' . DIRECTORY_SEPARATOR . $img.'.'.$ext);			
			$this->imgName = $this->input->post('img');
			return true;
		endif;
		return false;
	}
}